<template>
    <div class="gift-box">
        <el-form :model="giftData" :rules="rules" ref="giftData" inline label-width="120px" class="demo-ruleForm">
            <el-form-item label="关联游戏" prop="gameName" required>
                <selectGame :getGame="getGame" :gameInfo="giftData" />
            </el-form-item>
            <el-form-item label="发放对象" prop="giveUser" required>
                <el-select style="width: 220px;" v-model="giftData.giveUser">
                    <el-option v-for="(item, index) in userList" :key="index" :label="item" :value="index"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="发放渠道" prop="giveChanneel" required>
                <el-select style="width: 220px;" v-model="giftData.giveChanneel">
                    <el-option label="游戏时光宝箱" :value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="单人领取次数" prop="getTime" required>
                <el-input v-model="giftData.getTime" type="number" style="width:220px"></el-input>
            </el-form-item>
            <el-form-item label="发放时间" prop="giveTime" required>
                <el-date-picker
                    popper-class="channel-picker"
                    :picker-options="pickerOptions"
                    v-model="giftData.giveTime"
                    type="datetime"
                    @change="giveTimeChange"
                    placeholder="选择发放时间">
                </el-date-picker>
            </el-form-item>
           <el-form-item label="截止时间">
                <el-date-picker
                    popper-class="channel-picker"
                    :picker-options="pickerOptions"
                    v-model="giftData.endTime"
                    type="datetime"
                    @change="actEndTimeChange"
                    placeholder="选择截止时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="状态" prop="status" required>
                <el-radio-group v-model="giftData.status">
                    <el-radio :label="1">上架</el-radio>
                    <el-radio :label="0">下架</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <div class="giftInfo-box">
            <topTitle title="礼包信息" style="margin-bottom: 20px; padding-left:0px;"/>
            <el-button v-if="allExport" type="primary" @click="exportTrigger('all')">全部导出</el-button>
            <el-button type="primary" @click="addGift">添加礼包</el-button>
            <span>{{ giftData.rewardCount }}</span>
        </div>
        <div class="gift-item-wrap" v-for="(item, index) in giftData.boxActivityRewardVoList" :key="index">
            <el-form :model="item" :rules="rules" :ref="`giftData-${index}`" inline label-width="110px" class="demo-ruleForm">
                <el-form-item label="礼包内容" prop="rewardDesc" required>
                    <el-input v-model="item.rewardDesc" autosize type="textarea" style="width:300px"></el-input>
                </el-form-item>
                <el-form-item label="截止日期" prop="endTime" required>
                    <el-date-picker
                        popper-class="channel-picker"
                        :picker-options="pickerOptions"
                        v-model="item.endTime"
                        type="datetime"
                        @change="(val) => endTimeChange(val, index)"
                        placeholder="选择截止日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="礼包领取地址" prop="getUrl" required>
                    <el-input v-model="item.getUrl" type="input" style="width:300px"></el-input>
                </el-form-item>
                <div class="gift-item" v-for="(it, ind) in item.boxActivityRewardKeyVoList" :key="ind">
                    <p style="width: 40px;">第{{ ind + 1 }}批</p>
                    <p>总量：{{ it.importCount }}</p>
                    <p>已兑换：{{ it.exchangeCount || 0 }}</p>
                    <p>导入时间：{{ it.createTime || '-' }} </p>
                    <p class="menu">
                        <span v-if="!it.exchangeCount" class="span-btn" @click="deleteTrigger(it.importId, item.giftId, index, ind)">删除</span>
                        <span class="span-btn" @click="exportTrigger('key', item.giftId, it.importId)">导出</span>
                        <span class="span-btn" @click="openDialog(1, item.giftId, it.importId)">查看</span>
                    </p>
                </div>
                <div class="gift-btn">
                    <el-button style="margin-right: 20px;" type="primary" v-if="index > 0" @click="deleteTrigger('', item.giftId, index)">删除礼包</el-button>
                    <upload-excel-component v-if="giftData.activityId" style="margin-right: 20px;" :btnModel="true" btnText="导入礼包码" :uploadIndex="index" :on-success="handleSuccess" :before-upload="beforeUpload" />
                    <el-button v-if="giftData.activityId" type="primary" @click="exportTrigger('gift', item.giftId)">导出</el-button>
                </div>
            </el-form>
        </div>
        <div class="form-bottom">
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button type="primary" @click="cancelForm">取消</el-button>
        </div>
        <el-dialog title="礼包码详情" :visible.sync="dialogVisible" width="60%">
            <div class="input-box">
                <span class="input-title" style="margin-left: 0px;">兑换码状态</span>
                <el-select @change="selectChange" style="width:150px;" v-model="status">
                    <el-option label="全部" :value="null"></el-option>
                    <el-option label="已领取" :value="1"></el-option>
                    <el-option label="未领取" :value="0"></el-option>
                </el-select>
            </div>
            <div class="table-box">
                <el-table :data="tableData" max-height="450px" ref="table" border style="width: 100%">
                    <el-table-column min-width="150" prop="cdKey" label="兑换码"></el-table-column>
                    <el-table-column min-width="100" label="icon">
                        <template slot-scope="scope">
                            <div class="cover">
                                <img :src="scope.row.icon">
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="80" label="用户ID">
                        <template slot-scope="scope">
                            <span>{{ scope.row.userId || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="80" label="用户昵称">
                        <template slot-scope="scope">
                            <span v-if="scope.row.status === 1 && !scope.row.userName">测试领用</span>
                            <span v-else class="table-btn" @click="goUserDetail(scope.row.userId)">{{ scope.row.userName || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="80" label="状态">
                        <template slot-scope="scope">
                            <div v-if="scope.row.status === 1" style="color:#F56C6C;">已领取</div>
                            <div v-else style="color: #67C23A;">未领取</div>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="80" label="操作">
                        <template slot-scope="scope">
                            <div v-if="scope.row.status === 0">
                                <el-button @click="changeStatus(scope.row)" type="text" size="small">领取</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="tools">
                <el-pagination
                    @size-change="sizeChange"
                    @current-change="pageChange"
                    :current-page="pageNum"
                    :page-sizes="_pageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { formatDate } from '@/utils/utils'
import UploadExcelComponent from '@/components/global/uploadExcel/index.vue'
export default {
    name: 'UploadExcel',
    components: { UploadExcelComponent },
    data () {
        return {
            pageNum: 1,
            pageSize: this._pageSize,
            total: 0,
            status: null,
            tableData: [],
            giftData: {
                giveUser: 0,
                giveChanneel: 0,
                boxActivityRewardVoList: []
            },
            userList: ['全平台', '同游戏用户', '同游戏新用户', '同游戏老用户', '新用户', '老用户'],
            pickerOptions: {
                disabledDate (time) {
                    return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
                },
                selectableRange: '00:00:00 - 23:59:59'
            },
            rules: {
                gameName: [
                    { required: true, message: '请选择关联游戏', trigger: ['change'] }
                ],
                giveUser: [
                    { required: true, message: '请选择发放对象', trigger: ['blur'] }
                ],
                giveChanneel: [
                    { required: true, message: '请选择发放渠道', trigger: ['blur'] }
                ],
                giveTime: [
                    { required: true, message: '请选择发放时间', trigger: ['blur', 'change'] }
                ],
                status: [
                    { required: true, message: '请选择活动状态', trigger: ['change'] }
                ],
                getTime: [
                    { required: true, message: '请输入领取次数', trigger: ['blur', 'change'] }
                ],
                rewardDesc: [
                    { required: true, message: '请输入礼包内容', trigger: ['blur', 'change'] }
                ],
                endTime: [
                    { required: true, message: '请选择截止日期', trigger: ['blur', 'change'] }
                ],
                getUrl: [
                    { required: true, message: '请填写领取地址', trigger: ['blur', 'change'] }
                ]
            },
            allExport: false,
            dialogVisible: false
        }
    },
    created () {
        this.giftData.activityId = this.$route.query.id || null
        if (this.giftData.activityId) {
            this.getDetail()
        } else {
            this.giftData.boxActivityRewardVoList.push({
                rewardDesc: '',
                getUrl: '',
                rewardCount: 0,
                endTime: '',
                boxActivityRewardKeyVoList: []
            })
        }
    },
    methods: {
        getDetail () {
            this.$http.post('/lottrey/selectGiftList', {
                activityId: this.giftData.activityId
            }).then(res => {
                if (res.code === '0') {
                    this.giftData = res.data[0]
                    this.giftData.giveTime = this.giftData.giveTime && this.initTime(res.data[0].giveTime)
                    this.giftData.endTime = this.giftData.endTime && this.initTime(res.data[0].endTime)
                    this.giftData.boxActivityRewardVoList.map(item => {
                        item.endTime = item.endTime && this.initTime(item.endTime)
                        if (item.boxActivityRewardKeyVoList.length > 0) {
                            this.allExport = true
                            item.boxActivityRewardKeyVoList.map(it => {
                                it.createTime = it.createTime && this.initTime(it.createTime)
                            })
                        }
                    })
                } else {
                    this.$message({
                        type: 'error',
                        message: '系统异常，请稍后再试'
                    })
                }
            })
        },
        submitForm () {
            if (this.validateForm()) {
                // let flag = true
                // this.giftData.boxActivityRewardVoList.map(item => {
                //     if (item.boxActivityRewardKeyVoList.length < 1) flag = false
                // })
                // if (!flag && this.giftData.activityId) {
                //     return this.$message({
                //         type: 'error',
                //         message: '每个礼包至少上传一批礼包码！'
                //     })
                // }
                this.$http.post('/lottrey/updateBoxActivityVo', this.giftData).then(res => {
                    if (res.code === '0') {
                        let message = this.giftData.activityId ? '修改成功' : '创建成功'
                        this.$message({
                            type: 'success',
                            message
                        })
                        setTimeout(() => {
                            this.$router.push('/task/gift')
                        }, 1000)
                    } else {
                        this.$message({
                            type: 'error',
                            message: '系统异常，请稍后再试'
                        })
                    }
                })
            }
        },
        validateForm () {
            let flag = true
            this.$refs['giftData'].validate(valid => {
                if (!valid) {
                    flag = false
                }
            })
            for (let i in this.giftData.boxActivityRewardVoList) {
                this.$refs[`giftData-${i}`][0].validate(valid => {
                    if (!valid) {
                        flag = false
                    }
                })
            }
            return flag
        },
        deleteTrigger (importId, giftId, giftIndex, keyIndex) {
            if (!this.giftData.activityId || (!importId && keyIndex >= 0)) {
                if (keyIndex) {
                    this.giftData.boxActivityRewardVoList[giftIndex].boxActivityRewardKeyVoList.splice(keyIndex, 1)
                } else {
                    this.giftData.boxActivityRewardVoList.splice(giftIndex, 1)
                }
            } else {
                let params = {}
                if (keyIndex) {
                    params = { importId, giftId }
                } else {
                    let flag = true
                    this.giftData.boxActivityRewardVoList[giftIndex].boxActivityRewardKeyVoList.map(item => {
                        if (item.exchangeCount) flag = false
                    })
                    if (!flag) {
                        return this.$message({
                            type: 'warning',
                            message: '删除失败，礼包内包含已兑换的礼包码！'
                        })
                    }
                    params = { giftId }
                }
                this.$http.post('/lottrey/deleteActivityKey', params).then(res => {
                    if (res.code === '0') {
                        this.$message({
                            type: 'success',
                            message: '删除成功'
                        })
                        if (importId) {
                            this.giftData.boxActivityRewardVoList[giftIndex].boxActivityRewardKeyVoList.splice(keyIndex, 1)
                        } else {
                            this.giftData.boxActivityRewardVoList.splice(giftIndex, 1)
                        }
                    } else {
                        this.$message({
                            type: 'error',
                            message: '系统异常，请稍后再试'
                        })
                    }
                })
            }
        },
        addGift () {
            let gift = {
                rewardDesc: '',
                getUrl: '',
                rewardCount: 0,
                endTime: ''
                // createTime: '',
                // importCount: 0
            }
            this.giftData.boxActivityRewardVoList.push(gift)
        },
        getGame (val, index) {
            this.giftData = Object.assign(this.giftData, val)
        },
        openDialog (pageNum, giftId, importId) {
            let params = {
                pageNum,
                pageSize: this.pageSize,
                giftId,
                importId,
                status: this.status
            }
            this.currentGiftId = giftId
            this.currentImportId = importId
            this.$http.post('/lottrey/giftKeyDetail', params).then(res => {
                if (res.code === '0') {
                    this.tableData = res.data
                    this.total = res.count
                    this.dialogVisible = true
                } else {
                    this.$message({
                        type: 'error',
                        message: '系统异常，请稍后再试'
                    })
                }
            })
        },
        exportTrigger (type, giftId, importId) {
            let params = {
                activityId: this.giftData.activityId,
                giftId: null,
                importId: null
            }
            if (type === 'gift') {
                params.giftId = giftId
            }
            if (type === 'key') {
                params.giftId = giftId
                params.importId = importId
            }
            this.$http.post('/lottrey/exportActivityKey', params, {
                responseType: 'arraybuffer'
            }).then(res => {
                const aLink = document.createElement('a')
                let blob = new Blob([res], { type: 'application/vnd.ms-excel' })
                aLink.href = URL.createObjectURL(blob)
                aLink.setAttribute('download', '礼包兑换码' + '.xlsx') // 设置下载文件名称
                aLink.click()
            })
        },
        cancelForm () {
            this.$router.push('/task/gift')
        },
        giveTimeChange (val) {
            if (!val) {
                this.giftData.giveTime = null
            } else {
                this.giftData.giveTime = formatDate(val.getTime(), 'YYYY-MM-DD HH:MM:SS')
            }
        },
        actEndTimeChange (val) {
            if (!val) {
                this.giftData.endTime = null
            } else {
                this.giftData.endTime = formatDate(val.getTime(), 'YYYY-MM-DD HH:MM:SS')
            }
        },
        endTimeChange (val, index) {
            if (!val) {
                this.giftData.boxActivityRewardVoList[index].endTime = null
            } else {
                this.giftData.boxActivityRewardVoList[index].endTime = formatDate(val.getTime(), 'YYYY-MM-DD HH:MM:SS')
            }
        },
        initTime (time) {
            return formatDate(new Date(time), 'YYYY-MM-DD HH:MM:SS')
        },
        beforeUpload (file) {
            const isLt1M = file.size / 1024 / 1024 < 1
            if (isLt1M) {
                return true
            }
            this.$message({
                message: '上传文件不能大于1M',
                type: 'warning'
            })
            return false
        },
        handleSuccess ({ results, header, index, fileData }) {
            let formData = new FormData() // FormData 对象
            formData.append('file', fileData)
            formData.append('giftId', this.giftData.boxActivityRewardVoList[index].giftId)
            this.$http.post('/lottrey/importActivityKey', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }).then(res => {
                if (res.code === '0') {
                    this.allExport = true
                    this.giftData.boxActivityRewardVoList[index].boxActivityRewardKeyVoList.push({
                        importCount: results.length,
                        createTime: formatDate(new Date().getTime(), 'YYYY-MM-DD HH:MM:SS')
                    })
                } else {
                    this.$message({
                        type: 'error',
                        message: '系统异常，请稍后再试'
                    })
                }
            })
        },
        goUserDetail (id) {
            const { href } = this.$router.resolve({
                path: '/dataReport/userInfo',
                query: {
                    id
                }
            })
            window.open(href, '_blank')
        },
        selectChange () {
            this.openDialog(1, this.currentGiftId, this.currentImportId)
        },
        changeStatus (item) {
            this.$http.post('/lottrey/updateKeyStatus', {
                id: item.id,
                status: 1
            }).then(res => {
                if (res.code === '0') {
                    item.status = 1
                    this.$message({
                        type: 'success',
                        message: '领取成功'
                    })
                } else {
                    this.$message({
                        type: 'error',
                        message: '系统异常，请稍后再试'
                    })
                }
            })
        },
        // 页码切换
        sizeChange (val) {
            this.pageNum = 1
            this.pageSize = val
            this.openDialog(1, this.currentGiftId, this.currentImportId)
        },
        // 页容切换
        pageChange (val) {
            this.pageNum = val
            this.openDialog(this.pageNum, this.currentGiftId, this.currentImportId)
        }
    }
}
</script>
<style lang="scss" scoped>
    .gift-box {
        max-width: 800px;
        .table-tools {
            display: flex;
            width: 100%;
            .table-title {
                font-size: 14px;
                color: #606266;
            }
        }
        .gift-item-wrap {
            width: 640px;
            padding: 20px;
            margin: 20px 0 20px 50px;
            border: 1px solid #ccc;
            border-radius: 10px;
        }
        .giftInfo-box {
            margin: 20px 0;
            margin-left: 50px;
        }
        .gift-item {
            position: relative;
            display: flex;
            margin-bottom: 20px;
            margin-left: 40px;
            align-items: center;
            font-size: 14px;
            color: #606266;
            p {
                margin-right: 10px;
            }
            .menu {
                position: absolute;
                right: 0px;
            }
            .span-btn {
                margin-right: 5px;
                color: cadetblue;
                cursor: pointer;
            }
        }
        .gift-btn {
            margin-left: 40px;
        }
        .form-bottom {
            display: flex;
            width: 700px;
            justify-content: space-around;
        }
        /deep/.el-dialog__body {
            padding-top: 10px;
        }
    }
    .table-box {
        margin-bottom: 20px;
        .cover {
            width: 80px;
            height: 80px;
            > img {
                width: 100%;
                height: 100%;
            }
        }
        .table-btn {
            cursor: pointer;
            color: #409EFF;
            font-size: 13px;
            font-weight: 500;
            &:hover {
                text-decoration: underline;
            }
        }
    }
    .tools {
        padding-right: 20px;
        display: flex;
        justify-content: flex-end;
    }
    .input-box {
        margin-bottom: 10px;
        font-size: 13px;
        font-weight: 500;
        .input-title {
            margin: 0 10px 0 20px;
        }
        .btn {
            margin-top: 10px;
            margin-left: 10px;
        }
    }
</style>
